﻿using RabbitMQ.Client;
using System.Text;

namespace LS.Screening.UI.Common
{
    public static class RabbitMQProducer
    {
        #region 01 订阅发布(广播消费) 扇形交换机  一个生产者的消息同时给多个消费者

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="exchange"></param>
        /// <param name="message"></param>
        public static void PublishFanout(string exchange, string message)
        {
            using (var connection = PubSubMQConfig.GetConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: exchange, type: ExchangeType.Fanout);
                var body = Encoding.UTF8.GetBytes(message);
                var properties = channel.CreateBasicProperties();
                properties.Persistent = true; // 设置消息持久化
                channel.BasicPublish(exchange: exchange, routingKey: string.Empty, basicProperties: properties, body: body);
            }
        }

        #endregion

        #region 02 主题交换机

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="rabbitMQConfig"></param>
        /// <param name="queueName"></param>
        /// <param name="exchange"></param>
        /// <param name="routingKey"></param>
        /// <param name="message"></param>
        public static void PublishTopic(string exchange, string queueName, string routingKey, string message)
        {
            //1、建立连接
            using var connection = PubSubMQConfig.GetConnection();
            using var channel = connection.CreateModel();

            // 2、定义交换机
            channel.ExchangeDeclare(exchange: exchange, type: ExchangeType.Topic, true);
            channel.QueueDeclare(queueName, true, false, false, null);
            channel.QueueBind(queueName, exchange, routingKey);

            // 3、发送消息
            var body = Encoding.UTF8.GetBytes(message);
            var properties = channel.CreateBasicProperties();
            properties.Persistent = true; // 设置消息持久化
            channel.BasicPublish(exchange: exchange, routingKey: routingKey, basicProperties: properties, body: body);
        }

        #endregion
    }
}
